package com.soilflow.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.soilflow.common.core.domain.entity.GamesBetHistory;
import com.soilflow.common.core.domain.entity.GamesBidHistory;
import com.soilflow.common.core.domain.entity.GamesScoreHistory;
import com.soilflow.common.core.domain.entity.GamesUserScore;
import com.soilflow.common.domain.LandAuction;
import com.soilflow.common.domain.LandAuction2;
import com.soilflow.common.enums.BetChargeFee;
import com.soilflow.common.enums.BetRate;
import com.soilflow.info.service.LandAuctionService;
import com.soilflow.know.service.GamesBetHistoryService;
import com.soilflow.know.service.GamesBidHistoryService;
import com.soilflow.know.service.GamesScoreHistoryService;
import com.soilflow.know.service.GamesUserScoreService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author steven
 * @date 2023年12月15日 18:03:19
 */
@Component("UpdateAuctionStatusJon")
public class UpdateAuctionStatusJon {

    @Autowired
    private GamesBidHistoryService gamesBidHistoryService;

    @Autowired
    private GamesBetHistoryService gamesBetHistoryService;

    @Autowired
    private GamesUserScoreService gamesUserScoreService;
    @Autowired
    private GamesScoreHistoryService gamesScoreHistoryService;

    // 开奖定时任务，入口方法
    public void changeStatus() throws ParseException {

        // 启动计划任务
        gamesBidHistoryService.scheduler();

        /*String channelId = "http://www.huhongsheji.com/";
        GamesBidHistory data = this.spider(channelId);

        GamesBidHistory gamesBidHistory = gamesBidHistoryService.selectGamesBidHistoryByBidNo(data.getBidNo());
        if(gamesBidHistory == null){
            data.setCreateTime(new Date());
            // 开奖
            gamesBidHistoryService.insertGamesBidHisotry(data);
            // 派奖
            this.paiJiang(data);
        }

        System.out.println("定时任务爬取开奖数据。。。。");*/
    }

    public boolean idHuiBen(Integer number1, Integer number2, Integer number3){
        /**
         * 每天晚上7点到7点半维护半小时，其它时间正常运行
         * 7点半到7点 11.5小时 * 60 = 690分钟 / 3.5分钟
         * 回： 对子，顺子，豹子，13，14（3数之和） (0 1 2是顺子 0 8 9也是顺子 0 1 9也是顺子)
         */
        //情况1：顺子就是回 (0 1 2是顺子 0 8 9也是顺子 0 1 9也是顺子)
        if(number1 + 1 == number2 && number2 + 1 == number3){
            return true;
        }

        if(number1 == 0 && number2 == 8 && number3 == 9){
            return true;
        }

        if(number1 == 0 && number2 == 1 && number3 == 9){
            return true;
        }

        //情况2：对子也是回
        if(number1 == number2 || number2 == number3 || number1 == number3){
            return true;
        }

        //情况3：3数之和为13也是回
        if(number1 + number2 + number3 == 13){
            return true;
        }

        //情况4：3数之和为14也是回
        if(number1 + number2 + number3 == 14){
            return true;
        }

        return false;
    }

    // 派奖
    private void paiJiang(GamesBidHistory gamesBidHistory){
        // 这里有一个赔率的问题
        // 大小单双2.8的赔率，并且没有手续费
        // 第一步：查询所有的用户下注记录,逐步派奖
        List<GamesBetHistory> gamesBetHistories = gamesBetHistoryService.selectGamesBetHistoryListByBidNo(gamesBidHistory.getBidNo());
        for(GamesBetHistory item : gamesBetHistories){
            //  A 用户 中奖 100元，增加积分记录，修改用户总积分，设置投注记录为已开奖
            // 第一步：计算中奖金额
            BigDecimal prize = calPrizeAmount(item, gamesBidHistory);

            // 第二步：修改用户积分
            if(prize.doubleValue() == 0){
                continue;
            }else{
                this.updateUserScore(item, prize);
            }

            // 第三步：增加积分增加/减少记录
            this.insertScoreHistory(item, prize);

            // 第四步：修改投注信息为结算完成
            this.updateBetHistory(item, gamesBidHistory, prize);
        }
    }

    // 修改用户积分
    private void updateUserScore(GamesBetHistory item, BigDecimal prize){
        // 修改积分总额
        GamesUserScore gamesUserScore = new GamesUserScore();
        gamesUserScore.setUserId(item.getUserId());
        gamesUserScore.setScore(prize);
        gamesUserScoreService.addGamesUserScore(gamesUserScore);
    }

    // 添加中奖记录
    private void insertScoreHistory(GamesBetHistory item, BigDecimal prize){
        // 增加一条积分记录
        GamesUserScore newScore = gamesUserScoreService.selectGamesUserScoreByUserId(item.getUserId());
        GamesScoreHistory gamesScoreHistory = new GamesScoreHistory();
        gamesScoreHistory.setUserId(item.getUserId());
        gamesScoreHistory.setUserName(newScore.getUserName());
        gamesScoreHistory.setType("4");
        gamesScoreHistory.setScore(prize);
        gamesScoreHistory.setUserScore(newScore.getScore());
        gamesScoreHistory.setScoreTime(new Date());
        if(prize.doubleValue()>0){
            gamesScoreHistory.setOrigin("返奖");
        }else{
            gamesScoreHistory.setOrigin("亏损");
        }
        gamesScoreHistoryService.save(gamesScoreHistory);
    }

    // 修改投注记录
    private void updateBetHistory(GamesBetHistory gamesBetHistory, GamesBidHistory gamesBidHistory, BigDecimal prize){
        GamesBetHistory data = new GamesBetHistory();
        data.setBetId(gamesBetHistory.getBetId());
        data.setBidAmount(prize);
        data.setBidTime(gamesBidHistory.getBidTime());
        data.setBidNumber(gamesBidHistory.getBidNumber());
        data.setBidType(gamesBidHistory.getBidNumber());
        gamesBetHistoryService.updateGamesBetHistory(data);
    }

    private BigDecimal calPrizeAmount(GamesBetHistory bet, GamesBidHistory gamesBidHistory){
        // 计算用户的中奖金额(所有选项中奖之和)
        BigDecimal total = BigDecimal.ZERO;
        String[] split = bet.getBetData().split("\\+");
        for(String item : split){
            BigDecimal zhongjiangRate = getZhongjiangRate(item, gamesBidHistory.getBidType());
            BigDecimal bigDecimal = queryFee(item);
            BigDecimal amount = zhongjiangRate.subtract(bigDecimal).multiply(bet.getBetAmount()).divide(new BigDecimal(split.length), BigDecimal.ROUND_FLOOR);
            total = total.add(amount);
        }
        return total;
    }

    // 查询中奖赔率
    private BigDecimal getZhongjiangRate(String number, String type){
        ArrayList<String> jiang = new ArrayList<>();
        String[] split = type.split(",");
        if(split.length==3 && split[2].equals("回")){
            jiang.add(split[0]+split[2]);
            jiang.add(split[1]+split[2]);
            jiang.add(split[0]+split[1]+split[2]);
        }else{
            jiang.add(split[0]);
            jiang.add(split[1]);
            jiang.add(split[0]+split[1]);
        }
        for(int i=0; i<jiang.size(); i++){
            if(number.equals(jiang.get(i))){
                // 已经中奖了
                return queryRate(number);
            }
        }
        return new BigDecimal(0);
    }

    public BigDecimal queryRate(String code){
        for(BetRate item : BetRate.values()){
            if(code.equals(item.getCode())){
                return item.getRate();
            }
        }
        return BigDecimal.ZERO;
    }

    public BigDecimal queryFee(String code){
        for(BetChargeFee item : BetChargeFee.values()){
            if(code.equals(item.getCode())){
                return item.getRate();
            }
        }
        return BigDecimal.ZERO;
    }

    public GamesBidHistory spider(String url){

        GamesBidHistory data = new GamesBidHistory();
        data.setBidChannel(url);
        data.setGameId(1L);
        data.setBidTime(new Date());
        try {

            Document document = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36")
                    .timeout(8000)
                    .get();
            Elements issue = document.getElementsByClass("result-tr");

            Element item = issue.get(1);
            Elements span = item.getElementsByTag("span");
            System.err.println("开奖期数：" + span.get(0).html());
            data.setBidNo(span.get(0).html());

            String result = span.get(1).html();
            final int idx = result.indexOf("=");
            data.setBidNumber(result.substring(0, idx));

            System.out.println("9999999999999999999999999999");
            System.out.println( span.get(2).html());

            // 需要手动计算，开奖结果，直接抓取的内容是错误的
            String[] bidData = new String[3];
            String[] split = data.getBidNumber().split("\\+");
            Integer[] numbers = new Integer[3];
            numbers[0] = Integer.parseInt(split[0]);
            numbers[1] = Integer.parseInt(split[1]);
            numbers[2] = Integer.parseInt(split[2]);
            Arrays.sort(numbers);
            int sum = numbers[0] + numbers[1] + numbers[2];
            bidData[0] = (sum >= 14) ? "大":"小";
            bidData[1] = sum%2==0 ? "双":"单";
            bidData[2] = idHuiBen(numbers[0], numbers[1], numbers[2])?"回":"";

            data.setBidSum(sum+"");
            data.setBidType(String.join(",", bidData));

            System.err.println("开奖结果：" + span.get(1).html());
            System.err.println("中奖结果：" + span.get(2).html());
            System.out.println(String.join(",", bidData));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return data;

    }




}
